﻿using UnityEngine;
using System.Collections;

public class itemMoveTarget : MonoBehaviour {
	#region menber
	bool _isPlay;
	int _childCount;
	Transform[] childs;
	float saveTime;

	[SerializeField]bool autoPlay = false;
	[SerializeField]float startposX = 100;
	[SerializeField]float endPosX = 500;
	[SerializeField]float moveTime = 1;
	[SerializeField]float spacetime = 0.2f; //间隔时间

	#endregion

	#region Interface
	//外部调用的方法

	public void Play(){

		_isPlay = true;
		InitOther ();
		saveTime = Time.time;
		//将所有点归回原点
		for (int i = 0;i<_childCount;i++){

			MoveChild (i, 0);
		}

	}
	public void UnPlay(){

		for (int i = 0;i<_childCount;i++){

			MoveChild (i, 0);
		}
	}

	#endregion

	#region 内部实现方法
	// Use this for initialization
	void Start () {

	}
	void InitOther(){
		_childCount = transform.childCount;
		childs = new Transform[_childCount];
		for (int i = 0; i < _childCount; i++) {

			childs [i] = transform.GetChild (i);
		}
		if (moveTime == 0) {

			moveTime = 1;
		}
	}

	// Update is called once per frame
	void Update () {

		if (autoPlay) {
			autoPlay = false;
			Play ();
		}
		if (_isPlay) {
			
			for (int i = 0; i < _childCount; i++) {
				if (childs [i] != null) {

					float t = Mathf.Clamp ((Time.time - saveTime - i * spacetime)/moveTime, 0, 1);
					MoveChild (i, t);
					if (i == _childCount - 1 && t == 1) {
						_isPlay = false;
					}

				}
			}

		}
	}

	void MoveChild(int index,float time){

		Vector3 pos = childs [index].transform.localPosition;
		pos.x = Mathf.Lerp (startposX, endPosX, time);
		childs [index].transform.localPosition = pos;
	}

	#endregion

}
